"""
RAG服务工厂
根据配置选择不同的RAG实现
"""
from loguru import logger

from app.config import settings
from app.services.faiss_rag_service import faiss_rag_service

try:
    from app.services.milvus_rag_service import milvus_rag_service
    logger.info("Milvus RAG服务导入成功")
except Exception as e:
    logger.warning(f"导入Milvus RAG服务失败: {e}")
    milvus_rag_service = None


class RAGServiceFactory:
    """RAG服务工厂"""
    
    @staticmethod
    def get_rag_service():
        """
        根据配置获取RAG服务实例

        Returns:
            RAG服务实例
        """
        framework = settings.rag_framework.lower()
        vector_store = settings.vector_store_type.lower()

        logger.info(f"使用RAG框架: {framework}, 向量存储: {vector_store}")

        # 根据配置选择RAG服务
        if framework == "langchain" and vector_store == "milvus":
            if milvus_rag_service:
                logger.info("使用Milvus RAG服务")
                return milvus_rag_service
            else:
                logger.warning("Milvus RAG服务不可用，回退到FAISS RAG服务")
                return faiss_rag_service
        else:
            # 默认使用FAISS RAG服务（最稳定的选项）
            logger.info("使用FAISS RAG服务（默认）")
            return faiss_rag_service
    
    @staticmethod
    def get_available_implementations():
        """获取可用的实现列表"""
        return {
            "frameworks": ["langchain"],
            "vector_stores": ["faiss", "milvus"],
            "combinations": [
                {
                    "name": "LangChain + FAISS",
                    "framework": "langchain",
                    "vector_store": "faiss",
                    "description": "轻量级本地向量搜索，适合中小规模数据",
                    "pros": ["部署简单", "无需额外服务", "性能稳定"],
                    "cons": ["扩展性有限", "不支持分布式"]
                },
                {
                    "name": "LangChain + Milvus",
                    "framework": "langchain",
                    "vector_store": "milvus",
                    "description": "企业级向量数据库，支持大规模数据和分布式部署",
                    "pros": ["高扩展性", "支持分布式", "丰富的索引类型", "数据持久化"],
                    "cons": ["部署复杂", "资源消耗较大"]
                }
            ]
        }


# 全局RAG服务实例
def get_current_rag_service():
    """获取当前配置的RAG服务"""
    return RAGServiceFactory.get_rag_service()